#include"ResourceController.h"
#include"../ServerMaster.h"
#include"../GameServer.h"
#include"../DBMaster.h"
#include"../dbconnect/DBDao.h"
#include"../dbconnect/Model.h"

ResourceController::ResourceController(Object* master)
{
}

ResourceController::~ResourceController()
{
}

int ResourceController::addRes(const int& userId, const int& id, const int& size)
{
	auto master = dynamic_cast<ServerMaster*>(m_master);
	DBModel::Resource res;
	res.userId = userId;
	res.id = id;
	DBDao<DBModel::Resource> dao(master->getDBMaster()->getSqlConnnect());
	dao.setModel(res);
	auto list = dao.queryModel();
	if (list.size() >= 1)
	{
		auto item = list[0];
		item.num += size;
		dao.setModel(item);
		if (dao.updateModel("id=" + std::to_string(id) + " and userId=" + std::to_string(userId)))
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	else
	{
		res.num = size;
		dao.setModel(res);
		if (dao.insertModel())
		{
			return 1;
		}
		else
		{
			return 0;
		}

	}
}

int ResourceController::useRes(const int& userId, const int& id, const int& size)
{
	auto master = dynamic_cast<ServerMaster*>(m_master);
	DBModel::Resource res;
	res.userId = userId;
	res.id = id;
	DBDao<DBModel::Resource> dao(master->getDBMaster()->getSqlConnnect());
	dao.setModel(res);
	auto list = dao.queryModel();
	if (list.size() > 0)
	{
		auto item = list[0];
		if (item.num >= size)
		{
			item.num -= size;
			dao.setModel(item);
			if (dao.updateModel("id=" + std::to_string(id) + " and userId=" + std::to_string(userId)))
			{
				return 1;
			}
			else
			{
				return 0;
			}
		}
		else
		{
			return 0;
		}
	}
	else
	{
		return 0;
	}
}
